package cn.yinyu.queue.module.ecg.config;

import cn.yinyu.queue.module.ecg.Utils;
import cn.yinyu.queue.module.ecg.service.callingscreen.BigScreenConfig;
import cn.yinyu.queue.module.ecg.service.callingscreen.CallingScreenService;
import cn.yinyu.queue.module.ecg.service.config.EcgConfigService;
import cn.yinyu.queue.module.ecg.service.queue.QueueService;
import cn.yinyu.queue.module.ecg.service.queuesequence.QueueSequenceService;
import cn.yinyu.queue.module.infra.api.config.ConfigApi;
import cn.yinyu.queue.module.system.api.dict.DictDataApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.util.List;

import static cn.yinyu.queue.module.ecg.Constants.*;

@Component
@Slf4j
public class MySpringEventListener {

    @Resource
    private ConfigApi configApi;

    @Resource
    private DictDataApi dictDataApi;

    @Resource
    private EcgConfigService ecgConfigService;

    @Resource
    QueueService queueService;

    @Resource
    QueueSequenceService queueSequenceService;

    @Resource
    CallingScreenService callingScreenService;

    @EventListener
    public void onApplicationEvent(ApplicationStartedEvent event) {
        log.info("应用启动完成，系统初始。。。");

        queueService.initCheckType();

        ecgConfigService.readTimeSlotConfig();

        BigScreenConfig bigScreenConfig = new BigScreenConfig();
//        Integer waitingSize = Integer.valueOf(configApi.getConfigValueByKey(ECG_SCREEN_PANE_WAITING_KEY));
//        Integer passedSize = Integer.valueOf(configApi.getConfigValueByKey(ECG_SCREEN_PANE_PASSED_KEY));
//        bigScreenConfig.setWaitingSize( waitingSize);
//        bigScreenConfig.setPassedSize( passedSize);
//        callingScreenService.setBigScreenConfig(bigScreenConfig);
        callingScreenService.getDisplayColInfo();

        // 预约序号表 处理逻辑
        queueSequenceService.initQueueSequenceTable();

        String strOpenCloseTime = configApi.getConfigValueByKey(ECG_OPENING_TIME_KEY);
        List<LocalTime> list = Utils.parseOpeningTime(strOpenCloseTime);
        LocalTime openingTime = list.get(0);
        LocalTime closeTime = list.get(1);

        // 获取当前时间
        LocalTime currentTime = LocalTime.now();

        // 比较时间
        if (currentTime.isBefore(openingTime) || currentTime.isAfter(closeTime)) {
            queueService.closeBiz();
        } else {
            queueService.startBiz();
        }

        ecgConfigService.resetScheduler();
    }
}
